package gjwt

import (
	"gonexample/gone/config"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var (
	issuer    string
	jwtSecret []byte
	lifeTime  time.Duration
)

// Claims Claims
type Claims struct {
	UserID int `json:"uid"`
	jwt.StandardClaims
}

// Initialize Initialize
func Initialize() {
	issuer = config.App.Name
	lifeTime = config.App.JwtLifeTime
	jwtSecret = []byte(config.App.JwtSecret)
}

// GenerateToken generate tokens used for auth
func GenerateToken(uid int, password string) (string, error) {
	nowTime := time.Now()

	if lifeTime <= 0 {
		lifeTime = 7200 * time.Second
	}
	expireTime := nowTime.Add(lifeTime)

	claims := Claims{
		uid,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    issuer,
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

// ParseToken parsing token
func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}

// EncodeMD5 md5 encryption
// func EncodeMD5(value string) string {
// 	m := md5.New()
// 	m.Write([]byte(value))

// 	return hex.EncodeToString(m.Sum(nil))
// }
